package com.movie.dao;

import com.movie.model.User;
import com.movie.util.DBUtil;

import java.sql.*;

public class UserDao {

    // 检查登录是否成功
    public boolean checkLogin(String username, String password) {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, username);
                stmt.setString(2, password);
                try (ResultSet rs = stmt.executeQuery()) {
                    return rs.next(); // 如果结果集非空，说明有这个用户
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 用户注册
    public boolean registerUser(String username, String password) {
        try (Connection conn = DBUtil.getConnection()) {
            // 检查用户名是否已存在
            if (isUsernameTaken(username)) {
                return false; // 如果用户名已存在，返回false
            }

            // 插入新用户
            String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, username);
                stmt.setString(2, password); // 可以考虑加密密码
                return stmt.executeUpdate() > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 检查用户名是否已存在
    private boolean isUsernameTaken(String username) {
        String sql = "SELECT 1 FROM user WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, username);
            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next(); // 如果查询有结果，说明用户名已存在
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
